<template>
  <el-dialog
    v-model="dialogVisible"
    title="编辑个人资料"
    width="500px"
    :before-close="handleClose"
    class="edit-profile-dialog"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="昵称" prop="nickname">
        <el-input
          v-model="form.nickname"
          placeholder="请输入昵称"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="form.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
          <el-radio :label="0">保密</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="出生日期" prop="birthday">
        <el-date-picker
          v-model="form.birthday"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :disabled-date="disabledDate"
        />
      </el-form-item>

      <el-form-item label="个性签名" prop="signature">
        <el-input
          v-model="form.signature"
          type="textarea"
          placeholder="介绍一下自己吧"
          maxlength="100"
          show-word-limit
          :rows="3"
        />
      </el-form-item>

      <el-form-item label="头像">
        <div class="avatar-uploader">
          <div class="avatar-preview">
            <img :src="form.avatar || defaultAvatar" alt="头像预览" />
          </div>
          <el-upload
            class="avatar-upload"
            :auto-upload="false"
            action="#"
            :show-file-list="false"
            :on-change="handleAvatarChange"
            accept="image/jpeg,image/png,image/gif"
          >
            <el-button type="primary">更换头像</el-button>
          </el-upload>
        </div>
      </el-form-item>

      <el-form-item label="封面图">
        <div class="cover-uploader">
          <div
            class="cover-preview"
            :style="{ backgroundImage: `url(${form.cover || defaultCover})` }"
          ></div>
          <el-upload
            class="cover-upload"
            :auto-upload="false"
            action="#"
            :show-file-list="false"
            :on-change="handleCoverChange"
            accept="image/jpeg,image/png,image/gif"
          >
            <el-button type="primary">更换封面</el-button>
          </el-upload>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, defineProps, defineEmits, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import defaultAvatar from '@/assets/defaultuser.png'
import defaultCover from '@/assets/bg.avif'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  userInfo: {
    type: Object,
    default: () => ({
      nickname: '',
      signature: '',
      avatar: '',
      cover: '',
      gender: 0,
      birthday: '',
    }),
  },
})

const emit = defineEmits(['update:visible', 'updated'])

// 表单引用
const formRef = ref<FormInstance>()

// 对话框显示状态
const dialogVisible = ref(props.visible)

// 监听props.visible变化
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal
    if (newVal) {
      initForm()
    }
  },
)

// 监听dialogVisible变化
watch(
  () => dialogVisible.value,
  (newVal) => {
    emit('update:visible', newVal)
  },
)

// 表单数据
const form = reactive({
  nickname: props.userInfo.nickname || '',
  signature: props.userInfo.signature || '',
  avatar: props.userInfo.avatar || '',
  cover: props.userInfo.cover || '',
  gender: props.userInfo.gender || 0,
  birthday: props.userInfo.birthday || '',
  avatarFile: null as File | null,
  coverFile: null as File | null,
})

// 表单验证规则
const rules = reactive<FormRules>({
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' },
  ],
  signature: [
    { max: 100, message: '个性签名不能超过100个字符', trigger: 'blur' },
  ],
})

// 限制日期选择
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}

// 初始化表单数据
const initForm = () => {
  form.nickname = props.userInfo.nickname || ''
  form.signature = props.userInfo.signature || ''
  form.avatar = props.userInfo.avatar || ''
  form.cover = props.userInfo.cover || ''
  form.gender = props.userInfo.gender || 0
  form.birthday = props.userInfo.birthday || ''
  form.avatarFile = null
  form.coverFile = null
}

// 加载状态
const loading = ref(false)

// 处理头像上传
const handleAvatarChange = (file: any) => {
  // 限制文件大小为2MB
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过2MB!')
    return
  }

  // 更新预览
  form.avatarFile = file.raw
  form.avatar = URL.createObjectURL(file.raw)
}

// 处理封面上传
const handleCoverChange = (file: any) => {
  // 限制文件大小为5MB
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('上传封面图片大小不能超过5MB!')
    return
  }

  // 更新预览
  form.coverFile = file.raw
  form.cover = URL.createObjectURL(file.raw)
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true

      try {
        // 模拟上传文件并获取URL
        const avatarUrl = form.avatarFile
          ? await mockUploadFile(form.avatarFile)
          : form.avatar
        const coverUrl = form.coverFile
          ? await mockUploadFile(form.coverFile)
          : form.cover

        // 模拟API调用
        await new Promise((resolve) => setTimeout(resolve, 1000))

        // 更新用户信息
        const updatedUserInfo = {
          nickname: form.nickname,
          signature: form.signature,
          avatar: avatarUrl,
          cover: coverUrl,
          gender: form.gender,
          birthday: form.birthday,
        }

        emit('updated', updatedUserInfo)
        ElMessage.success('个人资料更新成功')
        dialogVisible.value = false
      } catch (error) {
        console.error('更新失败:', error)
        ElMessage.error('更新失败，请重试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 模拟文件上传
const mockUploadFile = async (file: File): Promise<string> => {
  // 实际项目中，这里应该是调用真实的文件上传API
  return new Promise((resolve) => {
    setTimeout(() => {
      // 返回临时的对象URL，实际项目中应该返回服务器上的URL
      resolve(URL.createObjectURL(file))
    }, 500)
  })
}
</script>

<style scoped lang="scss">
.edit-profile-dialog {
  .avatar-uploader,
  .cover-uploader {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .avatar-preview {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    overflow: hidden;
    border: 1px solid #e0e0e0;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .cover-preview {
    width: 240px;
    height: 90px;
    overflow: hidden;
    background-size: cover;
    background-position: center;
    border-radius: 4px;
    border: 1px solid #e0e0e0;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
